#!/usr/bin/python
# -*- coding:utf-8 -*-
# @author  : Chestnut
# @time    : 2025/6/24 15:26
# @function: What can I do.
# @version : V1
import tkinter
from tkinter import filedialog as fd, messagebox, filedialog, Tk
import re

from jupyter_core.version import pattern
from soupsieve.css_types import pickle_register


class TxtCut:
    def __init__(self):
        self.file = None

    def read_file(self):
        try:
            self.file.close()
        except:
            pass
        askfile = filedialog.askopenfilename(filetypes=[
            ("txt Files", "*.txt"),
            ("seabird capture Files", "*.cap"),
            ("All Files", "*.*")
        ])
        if askfile != "":
            f1 = open(askfile, "r")
            self.file = f1.read()
            self.file_name.set(askfile)
        else:
            self.file = None
            self.file_name.set(askfile)
            pass

    def cut_file(self, alpha=None):
        self.t1.delete("1.0", tkinter.END)
        if self.e0.get() != "" and self.e1.get() + self.e2.get() + self.e3.get() == "":
            "自由模式：直接在日期栏写入正则表达式或者想要找到的行（一定是以#作为行首）"
            self.t1.insert(tkinter.END, "正在以自由模式匹配……\n")
            matching = re.search(self.e0.get() + f"(#.*\n){{{int(self.e4.get())}}}", self.file)
            if matching != None:
                self.result = matching.group()
                self.t1.delete("1.0", tkinter.END)
                self.t1.insert(tkinter.END, self.result)
                self.t1.update()
            else:
                self.t1.insert(tkinter.END, "未匹配到任何数据")
        elif self.e0.get() == "" and self.e1.get() != "" and self.e2.get() != "" and self.e3.get() != "":
            "标准模式：在时间栏填入时分秒（24小时制）即可得到想要的行"
            self.t1.insert(tkinter.END, "正在以标准模式匹配……\n")
            matching = re.search(
                "(#.*)" + self.e1.get() + ':' + self.e2.get() + ':' + self.e3.get() + "(.*\n)" + f"(#.*\n){{{int(self.e4.get())}}}",
                self.file)
            if matching != None:
                self.result = matching.group()
                self.t1.delete("1.0", tkinter.END)
                self.t1.insert(tkinter.END, self.result)
                self.t1.update()
            else:
                self.t1.insert(tkinter.END, "未匹配到任何数据")
        elif self.e0.get() != "" and self.e1.get() != "" and self.e2.get() != "" and self.e3.get() != "":
            "扩展模式：在日期栏填入日期(yyyy-mm-dd)，并在时间栏填入时分秒（24小时制）即可得到想要的行"
            self.t1.insert(tkinter.END, "正在以扩展模式匹配……\n")
            matching = re.search(
                "(#.*)" + self.e0.get()+ " " + self.e1.get() + ':' + self.e2.get() + ':' + self.e3.get() + "(.*\n)" + f"(#.*\n){{{int(self.e4.get())}}}",
                self.file)
            if matching != None:
                self.result = matching.group()
                self.t1.delete("1.0", tkinter.END)
                self.t1.insert(tkinter.END, self.result)
                self.t1.update()
            else:
                self.t1.insert(tkinter.END, "未匹配到任何数据")

    def write_file(self, alpha=None):
        target_file = tkinter.filedialog.asksaveasfilename(filetypes=(['txt file','*.txt']))
        if target_file != "":
            if target_file.endswith(".txt"):
                t_f = open(target_file, "w", encoding="utf-8")
                t_f.write(self.result)
                t_f.close()
            else:
                t_f = open(target_file + '.txt', "w", encoding="utf-8")
                t_f.write(self.result)
                t_f.close()
        else:
            pass

    def main_window(self):
        root = tkinter.Tk()
        root.title("Txt Cut")
        root.resizable(False, False)

        self.file_name = tkinter.StringVar()
        self.file_name.set("")
        self.save_name = tkinter.StringVar()
        self.save_name.set("")

        root.bind("<Return>", self.cut_file)
        root.bind_all("<Control-s>", self.write_file)
        # 第一行
        Frm0 = tkinter.Frame(root)
        tkinter.Label(Frm0, text="Resource File:").pack(side=tkinter.LEFT)
        tkinter.Entry(Frm0, state="disabled", textvariable=self.file_name, width=70).pack(side=tkinter.LEFT)
        Frm0.pack(side=tkinter.TOP, fill=tkinter.X)
        # 第二行（输入）
        Frm1 = tkinter.Frame(root)
        tkinter.Label(Frm1, text="日期/表达式/次数").pack(side=tkinter.LEFT, padx=5)
        self.e0 = tkinter.Entry(Frm1, width=30);
        self.e0.pack(side=tkinter.LEFT, padx=5)  # 自由模式，当且仅当e0中有字符串的时候，匹配进入自由模式，即直接在e0中填写正则表达式
        tkinter.Label(Frm1, text="/").pack(side=tkinter.LEFT)
        self.e1 = tkinter.Entry(Frm1, width=5);
        self.e1.pack(side=tkinter.LEFT, padx=5)
        tkinter.Label(Frm1, text=":").pack(side=tkinter.LEFT)
        self.e2 = tkinter.Entry(Frm1, width=5);
        self.e2.pack(side=tkinter.LEFT, padx=5)
        tkinter.Label(Frm1, text=":").pack(side=tkinter.LEFT)
        self.e3 = tkinter.Entry(Frm1, width=5);
        self.e3.pack(side=tkinter.LEFT, padx=5)
        tkinter.Label(Frm1, text="/").pack(side=tkinter.LEFT)
        self.e4 = tkinter.Entry(Frm1, width=5);
        self.e4.pack(side=tkinter.LEFT, padx=5)

        Frm1.pack(side=tkinter.TOP, fill=tkinter.X)
        # 第三行（指令）
        Frm2 = tkinter.Frame(root)
        tkinter.Button(Frm2, text="Browse", command=self.read_file, width=20).pack(side=tkinter.LEFT, padx=5,
                                                                                   anchor=tkinter.CENTER, expand=True)
        tkinter.Button(Frm2, text="Cut", command=self.cut_file, width=20).pack(side=tkinter.LEFT, padx=5,
                                                                               anchor=tkinter.CENTER, expand=True)
        tkinter.Button(Frm2, text="Save", command=self.write_file, width=20).pack(side=tkinter.LEFT, padx=5,
                                                                                  anchor=tkinter.CENTER, expand=True)
        Frm2.pack(side=tkinter.TOP, fill=tkinter.X)
        # 第四行（输出）
        Frm3 = tkinter.Frame(root)
        tkinter.Label(Frm3, text="预览").pack(side=tkinter.TOP, fill=tkinter.X)
        self.t1 = tkinter.Text(Frm3, height=20);
        self.t1.pack(side=tkinter.LEFT, fill=tkinter.BOTH, expand=True)
        scb = tkinter.Scrollbar(Frm3, command=self.t1.yview);
        scb.pack(side=tkinter.LEFT, fill=tkinter.Y);
        self.t1.configure(yscrollcommand=scb.set)
        Frm3.pack(side=tkinter.TOP, fill=tkinter.X)

        root.mainloop()



myapp = TxtCut()
myapp.main_window()
